package com.example.demo.nio;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class BIO {

    public static void main(String[] args) {
        try {
            ServerSocket serverSocket = new ServerSocket(8888);
            System.out.println("当前BIO的监听地址。。。" + serverSocket.getLocalSocketAddress());
            while (true) {
                Socket clientAccept = serverSocket.accept();
                System.out.println("连接上的地址。。。" + clientAccept.getRemoteSocketAddress());
                try (Scanner input = new Scanner(clientAccept.getInputStream())) { // 输入流  阻塞。单线程
                    // 针对每个socket，不断进行数据交互
                    while (true) {
                        String request = input.nextLine();
                        if ("quit".equals(request)) {
                            break;
                        }
                        System.out.println(String.format("From %s : %s", clientAccept.getRemoteSocketAddress(), request));
                        String response = "From BIOServer Hello " + request + ".\n";
                        clientAccept.getOutputStream().write(response.getBytes());
                    }


                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
